/**
 * 文件描述如下：
 * 1. 批量保存
 * 2.
 * 3.
 * 4.
 */

import { mainStore } from '/src/store/mainStore.js'
import { _saveItem, _saveItemYaml, _saveItemJson, _saveItemStatic, _restartItem } from '/src/api/parameterConfiguration/index.js'
import { regInputValue } from './regInputValue.js'
import { rePamram } from './pageData.js'

export const saveItem_all = async () => {
  const store = mainStore()

  try {
    const params = {}
    const arrName = ['rsu', 'trafficlight', 'radar', 'lidar', 'camera']
    const arrName1 = ['motor-type', 'no-motor-type', 'special-no-motor-type', 'kf-r', 'kf-q-xy', 'kf-q-vxy', 'kf-q-axy', 'kf-p-xy', 'kf-p-vxy', 'kf-p-axy']
    const arrName2 = ['born-area-judge', 'no-motor-born-area-judge', 'angle-to-org', 'match-cam-ids', 'special-match', 'target-fix-param', 'lane-fitter-sets', 'subtend-cam-params', 'save-cam-params', 'motor-vehicle-labels']
    const arrName3 = ['focus-fix-params', 'curve-fix-params']
    const arrName4 = ['track-class']
    const arrName5 = ['video-class', 'conf-threshold', 'class-size', 'big-labels', 'camera-id']
    const arrName6 = ['camera-fix-0', 'camera-fix-1', 'camera-fix-2', 'camera-fix-3', 'camera-fix-4', 'camera-fix-5', 'camera-fix-6', 'camera-fix-7', 'camera-fix-8', 'camera-fix-9', 'camera-fix-10', 'camera-fix-11']

    for (let index = 0; index < store.saveAllData.length; index++) {
      const item = store.saveAllData[index]
      const { parentNode, key, inputType, arr } = item

      if (parentNode) {
        if (!params[parentNode]) params[parentNode] = {}
        if (arr) params[parentNode][key] = arr
        if (!arr) params[parentNode][key] = inputType == 'number' ? item.value - 0 : item.value
      } else {
        params[key] = inputType == 'number' ? item.value - 0 : item.value
      }

      // 修正后端接口涉及数组时 无法全局保存

      if (item.parentNode == 'fusion') {
        const params2 = {
          fusion: {},
        }

        params2.fusion[key] = item.value
        if (arr) params2.fusion[key] = arr
        _saveItem(store.cutArgPage, params2)
      }

      if (item.parentNode == 'mqtt' && item.key == 'sub-from-cloud-topics') {
        const params = {
          mqtt: {
            'sub-from-cloud-topics': item.arr,
          },
        }
        await _saveItem(store.cutArgPage, params)
      }

      if (item.parentNode == 'mqtt' && item.key == 'sub-from-dev-topics') {
        const params = {
          mqtt: {
            'sub-from-dev-topics': item.arr,
          },
        }
        await _saveItem(store.cutArgPage, params)
      }

      if (item.parentNode == 'algorithm' && item.key == 'pole-camera') {
        // 处理数据
        item.arr.forEach((ele) => {
          Object.keys(ele).forEach((keys) => {
            if (typeof ele[keys] == 'string') {
              ele[keys] = ele[keys].split(',')?.map(Number)
            }
          })
        })
        const param = {
          algorithm: {
            'pole-camera': item.arr,
          },
        }

        await _saveItem(store.cutArgPage, param)
      }

      if (item.parentNode == 'algorithm' && item.key == 'camera-param') {
        // 处理数据
        const param = {
          algorithm: {
            'camera-param': item.arr.map(Number),
          },
        }
        await _saveItem(store.cutArgPage, param)
      }

      // 感知组件的
      if (item.parentNode == null && arrName1.includes(item.key)) {
        const param = {}
        param[item.key] = item.arr.map(Number)

        await _saveItem(store.cutArgPage, param)
      }

      if (item.parentNode == null && arrName2.includes(item.key)) {
        const params = {}
        params[item.key] = item.arr
        params[key].forEach((ele) => {
          Object.keys(ele).forEach((keys) => {
            if (typeof ele[keys] == 'string') {
              ele[keys] = ele[keys].split(',')?.map(Number)
            }
          })
        })

        await _saveItem(store.cutArgPage, params)
      }

      if (item.parentNode == null && arrName3.includes(item.key)) {
        const params = {}
        params[item.key] = item.arr

        params[key].forEach((ele) => {
          Object.keys(ele).forEach((keys) => {
            if (typeof ele[keys] == 'object') {
              ele[keys].forEach((item) => {
                Object.keys(item).forEach((key2) => {
                  if (typeof item[key2] == 'string') {
                    item[key2] = item[key2].split(',').map(Number)
                  }
                })
              })
            }
          })
        })

        await _saveItem(store.cutArgPage, params)
      }

      if (item.parentNode == null && arrName4.includes(item.key)) {
        const params = {}
        params[item.key] = item.arr.split(',').filter(Boolean)
        await _saveItem(store.cutArgPage, params)
      }

      if (item.parentNode == null && arrName5.includes(item.key)) {
        const params = {}
        params[item.key] = item.arr
        await _saveItem(store.cutArgPage, params)
      }

      if (item.parentNode == null && arrName6.includes(item.key)) {
        const params = {}
        params[item.key] = item.arr
        params[key].forEach((ele) => {
          Object.keys(ele).forEach((keys) => {
            if (typeof ele[keys] == 'string') {
              ele[keys] = ele[keys].split(',')?.map(Number)
            }
          })
        })
        await _saveItem(store.cutArgPage, params)
      }
    }

    if (params.mqtt) {
      delete params.mqtt['sub-from-cloud-topics']
      delete params.mqtt['sub-from-dev-topics']
    }

    if (params.algorithm) {
      delete params.algorithm['pole-camera']
      delete params.algorithm['camera-param']
    }

    if (params.fusion) delete params.fusion

    arrName.forEach((item) => {
      if (params[item]) delete params[item]
    })

    arrName1.forEach((item) => {
      if (params[item]) delete params[item]
    })

    arrName2.forEach((item) => {
      if (params[item]) delete params[item]
    })

    arrName3.forEach((item) => {
      if (params[item]) delete params[item]
    })

    arrName4.forEach((item) => {
      if (params[item]) delete params[item]
    })

    arrName5.forEach((item) => {
      if (params[item]) delete params[item]
    })

    arrName6.forEach((item) => {
      if (params[item]) delete params[item]
    })

    await _saveItem(store.cutArgPage, params)

    // 在这里调用重启接口
    await restartItem(store)

    ElMessage.success('保存成功')
  } catch (error) {
    console.log(error)

    ElMessage.error('保存失败')
  }
}

// 往数组中添加需要保存的页面
export const pushAllUrlData = (params) => {
  const store = mainStore()

  let flage = false
  if (!params.arr) flage = regInputValue(params.value, params.inputType)
  if (params.arr) flage = true //数组放开检查

  // 校验不通过不处理
  if (flage === true) {
    store.saveAllData.push(params)

    const map = new Map() //通过map去重 并保留最新的数据

    store.saveAllData.forEach((item) => {
      const uniqueKey = `${item.parentNode}-${item.key}`
      map.set(uniqueKey, item) // 每次都会覆盖旧的，保留最新的
    })

    store.saveAllData = [...map.values()] // 转换为数组
  }
}

const restartItem = async (store) => {
  const res = await _restartItem(rePamram[store.cutArgPage])
  if (res?.data.code == 0) {
    ElMessage.success('重启成功')
  } else {
    ElMessage.error('重启失败')
  }
}
